package com.luyinbros.imagepicker;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.luyinbros.imagepicker.model.LocalMedia;
import com.luyinbros.imagepicker.model.LocalMediaFolder;
import com.luyinbros.imagepicker.util.LocalMediaLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:
 * resultCode=
 * Created by Andy Hong on 6/30/2017.
 */

public class ImagePreviewActivity extends AppCompatActivity implements ImagePreviewFragment.ActivityHandler {
    private ViewGroup mToolbar;
    private TextView actionDone;
    private CheckBox checkBox;
    private TextView tvTitle;
    private ViewPager mViewPager;
    private ViewGroup mBottomBar;

    private ImageDataHelper mHelper;
    private int maxSelectNum;
    private int currentPosition;
    private boolean isFullScreen = false;
    private String folderName;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        maxSelectNum = intent.getIntExtra("maxSelectNum", 1);
        currentPosition = intent.getIntExtra("startPosition", 0);
        mHelper = new ImageDataHelper((List<LocalMedia>) intent.getSerializableExtra("select"), maxSelectNum);
        folderName = intent.getStringExtra("folderName");


        setContentView(R.layout.activity_preview);

        mToolbar = (ViewGroup) findViewById(R.id.toolbar);
        actionDone = (TextView) findViewById(R.id.action_done);
        checkBox = (CheckBox) findViewById(R.id.checkbox);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        mViewPager = (ViewPager) findViewById(R.id.mViewPager);
        mBottomBar = (ViewGroup) findViewById(R.id.select_bar_layout);

        if (TextUtils.isEmpty(folderName)) {
            mHelper.setList((List<LocalMedia>) intent.getSerializableExtra("all"));
            initView();
        } else {
            //修复完毕 解决list过大intent无法传输的情况
            new LocalMediaLoader(this, LocalMediaLoader.TYPE_IMAGE).loadAllImages(new LocalMediaLoader.LocalMediaLoadListener() {
                @Override
                public void loadComplete(List<LocalMediaFolder> folders) {
                    if (folders != null && folders.size() != 0) {
                        for (LocalMediaFolder folder : folders) {
                            if (folderName.equals(folder.getName())) {
                                mHelper.setList(folder.getImages());
                                initView();
                                break;
                            }
                        }

                    }

                }
            });
        }

    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBack();
                finish();
            }
        });
        tvTitle.setText(String.format("%1$s/%2$s", currentPosition + 1, mHelper.allSize()));
        actionDone.setText(getString(R.string.format_image_num, mHelper.selectedSize(), maxSelectNum));
        mViewPager.setAdapter(new SimpleFragmentAdapter(getSupportFragmentManager()));
        mViewPager.setOffscreenPageLimit(5);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                if (mHelper.isSelected(mHelper.getItem(position))) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }
                tvTitle.setText(String.format("%1$s/%2$s", currentPosition + 1, mHelper.allSize()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setCurrentItem(currentPosition);

        checkBox.setChecked(mHelper.isSelected(mHelper.getItem(currentPosition)));
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isChecked = checkBox.isChecked();
                if (isChecked) {
                    if (mHelper.isMaxSelect()) {
                        Toast.makeText(ImagePreviewActivity.this, String.format(ImagePreviewActivity.this.getString(R.string.message_max_num), mHelper.getMaxSelectNum()), Toast.LENGTH_SHORT).show();
                        checkBox.setChecked(false);
                    } else {
                        mHelper.select(mHelper.getItem(currentPosition));
                        checkBox.setChecked(true);
                    }

                } else {
                    mHelper.removeSelect(mHelper.getItem(currentPosition));
                    checkBox.setChecked(false);
                }
                actionDone.setText(getString(R.string.format_image_num, mHelper.selectedSize(), maxSelectNum));
            }
        });
        actionDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBack();
                finish();
            }
        });
    }

    private void onBack() {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("select", (ArrayList<LocalMedia>) mHelper.getSelectList());
        setResult(1743, resultIntent);
    }


    @Override
    public void changeView() {
        mToolbar.setVisibility(isFullScreen ? View.GONE : View.VISIBLE);
        mBottomBar.setVisibility(isFullScreen ? View.GONE : View.VISIBLE);
        if (isFullScreen) {
            WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(attrs);
        } else {
            WindowManager.LayoutParams attrs = getWindow().getAttributes();
            attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(attrs);
        }
        isFullScreen = !isFullScreen;
    }

    private class SimpleFragmentAdapter extends FragmentPagerAdapter {
        public SimpleFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return ImagePreviewFragment.newInstance(mHelper.getItem(position).getPath());
        }

        @Override
        public int getCount() {
            return mHelper.allSize();
        }
    }
}
